import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {FormControl, FormGroup} from "@angular/forms";
import {Mess, MessFlag} from "./mess.bean";
import {RobotHttp} from "./robohttp.service";
import {ToastService} from "../../app/common/toast.service";

@Component({
  selector: 'page-robot',
  providers: [RobotHttp],
  templateUrl: './robot.html'
})
export class ContactPage {

  public messFormGroup: FormGroup;
  public messArray: Array<Mess> = new Array<Mess>();
  private limitCount: number = 5;

  constructor(public navCtrl: NavController, private robotHttp: RobotHttp,private toast:ToastService) {
    this.messFormGroup = new FormGroup({messInput: new FormControl()});
    this.messArray.push(new Mess(new Date(), "机器人：Hello!", MessFlag.robot));
  }

  pushMess(form: any) {
    let mess = form['messInput'];
    if (mess === null){
      mess = '';
    }
    this.messArray.push(new Mess(Date.now(),"我："+mess,MessFlag.me));
    console.log("get发送：",mess);

    this.robotHttp.pushMessTo(mess).subscribe(
      (res) => {
        console.log(res);
          let content = res['result']['content'];
          this.messArray.push(new Mess(new Date(),"机器人："+content,MessFlag.robot))
      },
      (err) => {
        console.error(err);
      },
      ()=>{
        console.log('请求完成')
        if (this.messArray.length>this.limitCount){
          this.toast.makeToast(`聊天条目超过${this.limitCount}，自动清理`,ToastService.MIDDLE_DURATION);
          this.messArray = this.messArray.slice(this.messArray.length/2,this.messArray.length-1);
        }
      }
    );

  }
}
